﻿using System;
using System.Net.Sockets;

namespace Grove.Server {

	public delegate void CrashedEventHandler(CrashedEventArgs e);

	public delegate void ShutdownEventHandler(ShutdownEventArgs e);

	public delegate void SocketConnectEventHandler(SocketConnectEventArgs e);

	public delegate void ServerStartedEventHandler();

	public class SocketConnectEventArgs : EventArgs {
		private readonly Socket mSocket;

		public SocketConnectEventArgs(Socket s) {
			mSocket = s;
			AllowConnection = true;
		}

		public Socket Socket {
			get { return mSocket; }
		}

		public bool AllowConnection { get; set; }
	}

	public class ShutdownEventArgs : EventArgs { }

	public class CrashedEventArgs : EventArgs {
		private readonly Exception mException;

		public CrashedEventArgs(Exception e) {
			mException = e;
		}

		public Exception Exception {
			get { return mException; }
		}

		public bool Close { get; set; }
	}


	public class Events {
		public static event CrashedEventHandler Crashed;
		public static event ShutdownEventHandler Shutdown;
		public static event SocketConnectEventHandler SocketConnect;
		public static event ServerStartedEventHandler ServerStarted;


		public static void InvokeServerStarted() {
			if (ServerStarted != null) {
				ServerStarted();
			}
		}


		public static void InvokeSocketConnect(SocketConnectEventArgs e) {
			if (SocketConnect != null) {
				SocketConnect(e);
			}
		}


		public static void InvokeShutdown(ShutdownEventArgs e) {
			if (Shutdown != null) {
				Shutdown(e);
			}
		}

		public static void InvokeCrashed(CrashedEventArgs e) {
			if (Crashed != null) {
				Crashed(e);
			}
		}


		public static void Reset() {
			Crashed = null;
			Shutdown = null;
			SocketConnect = null;
		}
	}
}